import dayjs from "dayjs";
import { message } from "@/utils/message";
// import { getUserList } from "@/api/system";
import { ElMessageBox } from "element-plus";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, computed, onMounted } from "vue";

export function dataSource() {
  const form = reactive({
    username: "",
    mobile: "",
    status: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const dialogFormVisible = ref(false);
  const dialogForm = ref();
  const dialogFormRef = reactive({
    dataSourceCode: "",
    dataSourceName: "",
    companyCode: "",
    state: ""
  });
  const dialogState = ref("");
  const dialogTitle = ref("");
  const validateName = (rule, value, callback) => {
    const title = /^[\A-\Z]+$/;
    if (value == "" || value == null || !value) {
      callback(new Error("请输入内容"));
    } else if (!title.test(value)) {
      callback(new Error("数据源编码限制只能为字符，最长10个字符，请修改!"));
    } else {
      callback();
    }
  };
  const rules = reactive({
    dataSourceCode: [
      { required: true, validator: validateName, trigger: ["blur"] }
    ],
    dataSourceName: [
      { required: true, message: "请输入数据源名称", trigger: ["blur"] }
    ],
    companyCode: [
      { required: true, message: "请输入公司编码", trigger: ["blur"] }
    ],
    state: [{ required: true, message: "请选择状态", trigger: ["blur"] }]
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      width: 70,
      hide: ({ checkList }) => !checkList.includes("序号列")
    },
    {
      label: "数据源编码",
      prop: "id",
      minWidth: 130
    },
    {
      label: "数据源名称",
      prop: "username",
      minWidth: 130
    },
    {
      label: "公司编码",
      prop: "nickname",
      minWidth: 130
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: ({ row }) => (
        <el-tag
          // size={scope.props.size === "small" ? "small" : "default"}
          // loading={switchLoadMap.value[scope.index]?.loading}
          type={row.status == 1 ? "success" : "info"}
          v-model={row.status}
          inline-prompt
          plain
          // onChange={() => onChange(scope as any)}
        >
          {row.status == 1 ? "开启" : "禁用"}
        </el-tag>
      )
    },
    {
      label: "创建时间",
      minWidth: 90,
      prop: "createTime",
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.username
      }</strong>用户吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          message("已成功修改用户状态", {
            type: "success"
          });
        }, 300);
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
  }

  function handleUpdate(row) {
    console.log(row);
  }

  function handleDelete(row) {
    console.log(row);
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function openDialog(type: string, row?: {}) {
    dialogState.value = type;
    if (type == "add") {
      dialogTitle.value = "新增数据源";
    } else {
      dialogTitle.value = "修改数据源";
      console.log(row);
    }
    dialogFormVisible.value = true;
  }

  function submitDialog() {
    dialogForm.value.validate(validate => {
      if (validate) {
        dialogFormVisible.value = false;
      }
    });
  }

  function handleClose() {
    dialogForm.value.clearValidate();
    dialogFormVisible.value = false;
  }

  async function onSearch() {
    loading.value = true;
    // const { data } = await getUserList();
    const data = {
      list: [
        {
          username: "中储南京智慧物流科技有限公司",
          nickname: "comany",
          remark: "管理员",
          deptId: 103,
          postIds: [1],
          mobile: "15888888888",
          sex: 0,
          id: "ZCZB",
          status: 0,
          createTime: 1609837427000,
          dept: { id: 103, name: "研发部门" }
        },
        {
          username: "pure",
          nickname: "pure",
          remark: "不要吓我",
          deptId: 104,
          postIds: [1],
          mobile: "15888888888",
          sex: 0,
          id: 100,
          status: 1,
          createTime: 1609981637000,
          dept: { id: 104, name: "市场部门" }
        },
        {
          username: "小姐姐",
          nickname: "girl",
          remark: null,
          deptId: 106,
          postIds: null,
          mobile: "15888888888",
          sex: 1,
          id: 103,
          status: 1,
          createTime: 1610553035000,
          dept: { id: 106, name: "财务部门" }
        },
        {
          username: "小哥哥",
          nickname: "boy",
          remark: null,
          deptId: 107,
          postIds: [],
          mobile: "15888888888",
          sex: 0,
          id: 104,
          status: 0,
          createTime: 1611166433000,
          dept: { id: 107, name: "运维部门" }
        }
      ],
      total: 4
    };
    dataList.value = data.list;
    pagination.total = data.total;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    buttonClass,
    dialogFormVisible,
    dialogFormRef,
    dialogForm,
    rules,
    dialogTitle,
    dialogState,
    handleClose,
    submitDialog,
    openDialog,
    onSearch,
    resetForm,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
